package com.cn.web.menu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cn.exception.MyException;
import com.cn.menu.ButtonsDO;
import com.cn.page.PageVo;
import com.cn.web.menu.mapper.IButtonMapper;
import com.cn.web.menu.service.ButtonService;
import com.cn.web.menu.service.MenuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * description: ButtonService <br>
 * date: 23.2.6 14:54 <br>
 * author: cn_yaojin <br>
 * version: 1.0 <br>
 */
@Service
@Slf4j
public class ButtonServiceImpl implements ButtonService {

    @Autowired
    private IButtonMapper buttonMapper;

    @Autowired
    private MenuService menuService;

    private void checkExsit(ButtonsDO info, QueryWrapper<ButtonsDO> search) {
        if (info.getId() != null && info.getId() > 0) {
            search.ne("id", info.getId());
        }
        long count = this.buttonMapper.selectCount(search);
        if (count > 0) {
            throw new MyException("按钮已经存在");
        }
    }

    @Override
    public void edit(ButtonsDO info) {
        QueryWrapper<ButtonsDO> search = new QueryWrapper<>();
        search.eq("no", info.getNo());
        checkExsit(info, search);
        search.clear();
        search.eq("name", info.getName());
        checkExsit(info, search);

        if (info.getId() == null || info.getId() <= 0) {
            this.buttonMapper.insert(info);
        } else {
            this.buttonMapper.updateById(info);
        }
        menuService.reloadButton();
    }

    @Override
    public List<ButtonsDO> list(ButtonsDO search) {
        QueryWrapper<ButtonsDO> queryWrapper = new QueryWrapper<>();
        if (search != null) {
            if (StringUtils.isNotEmpty(search.getName())) {
                queryWrapper.eq("name", search.getName());
            }
            if (StringUtils.isNotEmpty(search.getNo())) {
                queryWrapper.eq("no", search.getNo());
            }
        }
        return this.buttonMapper.selectList(queryWrapper);
    }

    @Override
    public PageInfo<ButtonsDO> page(PageVo<ButtonsDO> pageVo) {
        return PageHelper.startPage(pageVo.getPageNum(), pageVo.getPageSize()).doSelectPageInfo(() -> {
            list(pageVo.getParam());
        });
    }

    @Override
    public void del(String id) {
        this.buttonMapper.deleteById(id);
        menuService.reloadButton();
    }

}
